package com.hnhuas.salary.modules.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnhuas.salary.common.utils.FileHandleUtil;
import com.hnhuas.salary.common.utils.PageUtils;
import com.hnhuas.salary.common.utils.R;
import com.hnhuas.salary.modules.admin.entity.SalaryPayEntity;
import com.hnhuas.salary.modules.admin.service.SalaryPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wf.jwtp.annotation.RequiresRoles;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工资接口
 * Created by weirdor on 2019-08-24 00:30
 */
@RestController
@RequestMapping("/admin/pay")
public class SalaryPayController {


    @Autowired
    private SalaryPayService salaryPayService;


    public static Map<String, String> NAME_MAPPER = new HashMap<>();

    static {

        NAME_MAPPER.put("姓名", "name");
        NAME_MAPPER.put("岗位工资职务工资", "gwgzzwgz");
        NAME_MAPPER.put("级别工资", "jbgz");
        NAME_MAPPER.put("技术等级工资", "jsdjgz");
        NAME_MAPPER.put("交通补贴", "jtbt");
        NAME_MAPPER.put("工改保留津贴", "ggbljt");
        NAME_MAPPER.put("警衔津贴", "jxjt");
        NAME_MAPPER.put("工作津贴", "gzjt");
        NAME_MAPPER.put("生活补贴", "shbt");
        NAME_MAPPER.put("执勤津贴", "zqjt");
        NAME_MAPPER.put("回维补贴及卫生费", "hwbtjwsf");
        NAME_MAPPER.put("月绩效", "yjx");
        NAME_MAPPER.put("补发工资", "bfgz");
        NAME_MAPPER.put("应发工资", "yfgz");

        NAME_MAPPER.put("个人所得税上月调整", "grsdssydz");
        NAME_MAPPER.put("个人所得税", "grsds");
        NAME_MAPPER.put("住房公积金", "zfgjj");
        NAME_MAPPER.put("医疗费统筹", "ylftc");
        NAME_MAPPER.put("养老保险", "ylbx");
        NAME_MAPPER.put("职业年金", "zynj");
        NAME_MAPPER.put("实发工资", "sfgz");
    }


    /**
     * 导入工资信息
     */
    @RequiresRoles("admin")
    @PostMapping("upload")
    public R importPay(@RequestParam("file") MultipartFile file, Long time) {
        if (time==null){
            return R.error("");
        }

        if (file.isEmpty()) {
            return R.error(404, "文件不存在");
        }
        try {

            // 文件原始名称
            String originalFileName = file.getOriginalFilename();
            String suffix = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            // 保存到磁盘
            File outFile;
            String path;
            path = getDate() + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
            outFile = new File(File.listRoots()[0], "/upload/" + path);
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            file.transferTo(outFile);

//            String path = FileHandleUtil.upload(file.getInputStream(), "/", file.getOriginalFilename());

            ExcelReader reader = ExcelUtil.getReader("/upload/" + path);
            //获取到最后的一位
            int end = reader.getSheet().getLastRowNum();

            List<Map<String, Object>> readAll = reader.read(5, 1, end - 1);

            readAll.stream().forEach(k->{

                SalaryPayEntity salaryPayEntity=new SalaryPayEntity();
                salaryPayEntity.setTime(time);

                Map<String, String> map=new HashMap<>();

                k.entrySet().stream().forEach(l -> {
                    String key = l.getKey();
                    Object value = l.getValue();
                    if ("姓名".equals(key)){
                        salaryPayEntity.setName(Convert.toStr(value));
                    }
                    if ("身份证号".equals(key)){
                        salaryPayEntity.setIdCard(Convert.toStr(value));
                        map.put("身份证号",Convert.toStr(value));
                    }else {
                       if (NumberUtil.isNumber(Convert.toStr(value))){
                           Double c =Convert.toDouble(value);
                           value= NumberUtil.decimalFormat("0.00", c);
                       }
                        map.put(key,Convert.toStr(value));

                    }

            });

                salaryPayEntity.setSalaryData(JSON.toJSONString(map));

                QueryWrapper<SalaryPayEntity> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("name",salaryPayEntity.getName());
                queryWrapper.eq("time",time);
               int count= salaryPayService.count(queryWrapper);
               if (count==0){
                   salaryPayService.save(salaryPayEntity);
               }else{
                   List<SalaryPayEntity> list = salaryPayService.list(queryWrapper);

                   salaryPayEntity.setId(list.get(0).getId());
                   salaryPayService.updateById(salaryPayEntity);
               }

           });

            return R.ok().put("data", salaryPayService.list());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();


    }

    /**
     * 根据姓名查询工资
     *
     */
    @RequiresRoles("admin")
    @GetMapping("findByName")
    public  R findByName(Map<String, Object> params,String id_card,Long time){
        QueryWrapper<SalaryPayEntity> queryWrapper=new QueryWrapper<>();
        if(!"".equals(id_card)){
            queryWrapper.eq("id_card",id_card);
        }
        queryWrapper.eq("time",time);
        PageUtils page = salaryPayService.queryPageByTime(params,queryWrapper);
        return R.ok().put("data",page);
    }

    @GetMapping("findByTime")
    public  R findByTime(Map<String, Object> params,Long start_time,Long end_time,String id_card){
        if (end_time < start_time){
            return R.error(400, "开始时间不能大于结束时间");
        }
        QueryWrapper<SalaryPayEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id_card",id_card);
        queryWrapper.ge("time",start_time);
        queryWrapper.le("time",end_time);
        queryWrapper.orderByDesc("time");
        List<SalaryPayEntity> list = salaryPayService.list(queryWrapper);
        return R.ok().put("data",list);
    }


    // 获取当前日期
    private String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        return sdf.format(new Date());
    }

}
